//
//  SLHomeSlidMenuView.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/10.
//

#import "SLDeviceSettingVC.h"
#import "SLDeviceSettingCell.h"
#import "SLChangeNotifyVC.h"
#import "SLBridgeInfoVC.h"
#import "SLUpdateFirmVC.h"
#import "SLNearByVC.h"

static  NSString *const kCellId = @"SLDeviceSettingCell";
@interface SLDeviceSettingVC ()<UITableViewDelegate,UITableViewDataSource,XZPickViewDelegate,XZPickViewDataSource>{

}

@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)XZPickView *voicePicker;
@property (nonatomic, strong)NSArray *voiceArray;
@property (nonatomic, strong)NSString *curVoice;
@property (nonatomic, strong)NSDictionary *settingInfo;
@property (nonatomic, strong)NSDictionary *baseInfo;
@property (nonatomic, strong)NSDictionary *statusInfo;
@property (nonatomic, strong)SLDeviceSettingModel *emailCellModel;

@property (nonatomic, assign)BOOL isFirstLoad;
@end

@implementation SLDeviceSettingVC

-(void)viewDidLoad{
    [super viewDidLoad];
    _isFirstLoad = YES;
    [self configDatas];
    [self getDeviceData];
    [self setUpSubViews];
}

//获取硬件数据
-(void)getDeviceData{
    [ZCTool showLoadingOnKeyWindow];
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccess) {
            [self refresSubViews];
            return;
        }
        //获取硬件数据
        [self getDeviceSettingData];
    }];
}

-(void)getDeviceSettingData{
    __block NSInteger count = 3;
    //设置数据
    kWeakSelf(self);
    [[SLBluetoothManager sharedManager] getDeviceSettingInfo:^(id data) {
        count --;
        weakself.settingInfo = data;
        if (count == 0) [self refresSubViews];
    }];
    
    //硬件数据
    [[SLBluetoothManager sharedManager] getDeviceBaseInfo:^(id data) {
        count --;
        weakself.baseInfo = data;
        if (count == 0) [self refresSubViews];
    }];
    
    //状态数据
    [[SLBluetoothManager sharedManager] getDeviceStatusInfo:^(id data) {
        count --;
        weakself.statusInfo = data;
        if (count == 0) [self refresSubViews];
    }];
}

-(void)refreshSettingInfo{
    kWeakSelf(self);
    [[SLBluetoothManager sharedManager] getDeviceSettingInfo:^(id data) {
        weakself.settingInfo = data;
       [self refresSubViews];
    }];
}

//根据设备数据刷新页面还是服务端数据
-(void)refresSubViews{
    //每一次获取到设备信息全部同步到云端
    if (_isFirstLoad && _settingInfo && _baseInfo && _statusInfo) {
        _isFirstLoad = NO;
        [self sysncAllSettingInfo];
    }
    [self configDatas];
    [_tableView reloadData];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Lock management");
    [self.view addSubview:self.tableView];
    [self configPickers];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 70)];
    ZKBaseButton *sureBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(0, 10, kScreenWidth-40, 50);
    sureBtn.btnStyle = 2;
    [sureBtn setTitle:kLocalString(@"Delete and reset lock") forState:UIControlStateNormal];
    [footView addSubview:sureBtn];
    [sureBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footView;
}

#pragma mark -
#pragma mark - ================<修改配置>===============
-(void)switchSettingWith:(NSInteger)isOpen model:(SLDeviceSettingModel *)model{
    NSString *title = model.title;
    kWeakSelf(self);
    [ZCTool showLoadingOnKeyWindow];
    if ([title isEqualToString:kLocalString(@"Email notification")]){
        [self uploadSettingInfoWith:@"isOpenPush" value:kSTRING(@(isOpen)) needShowToast:YES];
        return;
    }
    
    [ZCTool connectDeviceWith:kCurClickDevice toast:@"" finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            [ZCTool hideLoadingOnKeyWindow];
            [weakself refresSubViews];
            return;
        }
        [self switchDeviceSettingWith:isOpen model:model];
    }];
}

//需要和硬件交互的
-(void)switchDeviceSettingWith:(NSInteger)isOpen model:(SLDeviceSettingModel *)model{
    NSString *title = model.title;
    kWeakSelf(self);
    //震动报警
    if ([title isEqualToString:kLocalString(@"Striking alarm")]) {
        [[SLBluetoothManager sharedManager] setVibrationAlarm:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenStrikingAlarm" value:kSTRING(@(isOpen))];
        }];
    }
    //高温报警
    else if ([title isEqualToString:kLocalString(@"Burning alarm")]){
        [[SLBluetoothManager sharedManager] setBurningAlarm:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenBurningAlarm" value:kSTRING(@(isOpen))];
        }];
    }
    //wifi开锁
    else if ([title isEqualToString:kLocalString(@"Disable unlock via Wi-fi")]){
        [[SLBluetoothManager sharedManager] setAllowWifiOpenModel:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenWifiModel" value:kSTRING(@(isOpen))];
        }];
    }
    //蓝牙开锁
    else if ([title isEqualToString:kLocalString(@"Disable unlock via Bluetooth")]){
        [[SLBluetoothManager sharedManager] setAllowBlueToothOpenModel:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenBlueToothModel" value:kSTRING(@(isOpen))];
        }];
    }
    //双模模式
    else if ([title isEqualToString:kLocalString(@"Dual-mode biometric")]){
        [[SLBluetoothManager sharedManager] setDbModel:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            if (isSuccess) kCurClickDevice.isOpenDbModel = isOpen;
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenDbModel" value:kSTRING(@(isOpen))];
        }];
    }
    //节能模式
    else if ([title isEqualToString:kLocalString(@"Energy saving mode")]){
        [[SLBluetoothManager sharedManager] setEnergyModel:isOpen finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            if (isSuccess) kCurClickDevice.isOpenEnergyModel = isOpen;
            [weakself hanldeSettingFinish:isSuccess key:@"isOpenEnergyModel" value:kSTRING(@(isOpen))];
        }];
    }
    //待实现
    else{
        [ZCTool hideLoadingOnKeyWindow];
    }
}

//处理设置结果
-(void)hanldeSettingFinish:(BOOL)isSuccess key:(NSString *)key value:(NSString *)value{
    [ZCTool hideLoadingOnKeyWindow];
    if (!isSuccess) {
        [self refresSubViews];
        kShowToast(@"Set faild");
        return;
    }
    [self refreshSettingInfo];
    //同步到云端
    [self uploadSettingInfoWith:key value:value needShowToast:NO];
}

//将配置同步到云端 - 单项配置同步
-(void)uploadSettingInfoWith:(NSString *)key value:(NSString *)value needShowToast:(BOOL)needShowToast{
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setObject:value forKey:key];
    if ([key isEqualToString:@"isOpenPush"] && [value isEqualToString:@"0"]) {
        [params setObject:@"" forKey:@"pushEmail"];
    }
    
    [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            if (needShowToast){
                kShowToast(message);
                [ZCTool hideLoadingOnKeyWindow];
            }
            [self refresSubViews];
            return;
        }
        //同步成功
        if (needShowToast) {
            [ZCTool hideLoadingOnKeyWindow];
        }
        if ([key isEqualToString:@"isOpenPush"]) {
            kCurClickDevice.isOpenPush = [value boolValue];
            [self refresSubViews];
            kNotifyRefreshDevcieList;
        }
    }];
}

//将硬件端的配置同步到云端 - 全部配置
-(void)sysncAllSettingInfo{
    NSDictionary *params = @{@"isOpenBurningAlarm":_settingInfo[@"isOpenBurningAlarm"],
                             @"isOpenStrikingAlarm":_settingInfo[@"isOpenStrikingAlarm"],
                             @"isOpenDbModel":_settingInfo[@"isOpenDbModel"],
                             @"isOpenBlueToothModel":_settingInfo[@"isOpenBlueToothModel"],
                             @"isOpenWifiModel":_settingInfo[@"isOpenWifiModel"],
                             @"isOpenEnergyModel":_settingInfo[@"isOpenEnergyModel"],
                             @"voice":_settingInfo[@"voice"],
                             @"mac":_baseInfo[@"mac"],
                             @"serialNumber":_baseInfo[@"sn"],
                             @"firmware":_baseInfo[@"version"],
                             @"deviceElectricQty":_statusInfo[@"batteryLevel"]};
    [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (isSuccessed) {
            kNotifyRefreshDevcieList;
        }
    }];
}

-(void)deleteAction{
//    [self deleteServiceData];
//    return;
    [SLTipAlertView showWith:kLocalString(@"Are you sure you want to delete this lock?") content1:kLocalString(@"This action will completely reset the lock to its factory settings. All stored fingerprints and e-keys will be permanently erased and cannot be recovered.") content2:@"" doneBtn:kLocalString(@"Delete and reset lock") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 0) {
            return;
        }
        //1.先连接设备
        [ZCTool showLoadingOnKeyWindow];
        [ZCTool connectDeviceWith:kCurClickDevice toast:@"" finish:^(BOOL isSuccess) {
            if (!isSuccess) {
                [ZCTool hideLoadingOnKeyWindow];
                return;
            }
            kCurDevice = kCurClickDevice;
            //2.服务器解绑
            NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo};
            [ZKHttpManager postWithPath:@"/msl_user/UnBindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString    * _Nonnull serMessage) {
                
                if (!isSuccessed) {
                    [ZCTool hideLoadingOnKeyWindow];
                    kShowToast(serMessage);
                    return;
                }
                //3.硬件解绑
                [[SLBluetoothManager sharedManager] unBindDeviceWith:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
                    if (!isSuccess) {
                        [ZCTool hideLoadingOnKeyWindow];
                        kShowToast(@"Unbind faild");
                        return;
                    }
                    
                    [[SLBluetoothManager sharedManager] disConnectPeripheral];
                    kShowToast(@"Delete success!");
                    kNotifyRefreshDevcieList;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            }];
        }];
    }];
}

-(void)deleteServiceData{
    //服务器解绑
    NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo};
    [ZKHttpManager postWithPath:@"/msl_user/UnBindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString    * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            //失败了重新绑定下
            [[SLBluetoothManager sharedManager] bindDeviceWith:nil];
            kShowToast(message);
            return;
        }
        [[SLBluetoothManager sharedManager] disConnectPeripheral];
        kShowToast(@"Delete success!");
        kNotifyRefreshDevcieList;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }];
}

-(void)configDatas{
    
    
    [self.dataArray removeAllObjects];
    NSMutableArray *section1 = [NSMutableArray new];
//    NSArray *titles1 = @[kLocalString(@"Lock name"),kLocalString(@"Disable unlock via Wi-fi"),kLocalString(@"Disable unlock via Bluetooth"),kLocalString(@"Set hot area")];
//    NSArray *titles1 = @[kLocalString(@"Lock name"),kLocalString(@"Dual-mode biometric"),kLocalString(@"Energy saving mode")];
    NSArray *titles1 = @[kLocalString(@"Lock name"), kLocalString(@"Energy saving mode")];
    
    [titles1 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        SLDeviceSettingModel *model = [SLDeviceSettingModel new];
        model.title = title;
        model.sectionName = kLocalString(@"Main settings");
        if ([title isEqualToString:kLocalString(@"Lock name")]) {
            model.content = kCurClickDevice.deviceName;
            model.contentColor = KColor_O;
        } else if ([title isEqualToString:kLocalString(@"Dual-mode biometric")]){
            model.style = 2;
            model.switchValue = _settingInfo ? _settingInfo[@"isOpenDbModel"] : kSTRING(@(kCurClickDevice.isOpenDbModel));
            model.desc = kLocalString(@"Uses proximity sensing and fingerprint recognition for higher accuracy in tough environments. May require a touch to wake before unlocking.");
        } else if ([title isEqualToString:kLocalString(@"Energy saving mode")]){
            model.style = 2;
            model.switchValue = _settingInfo ? _settingInfo[@"isOpenEnergyModel"] : kSTRING(@(kCurClickDevice.isOpenEnergyModel));
            model.desc = kLocalString(@"When “Energy saving mode” is enabled, you need to touch the fingerprint sensor to wake up the padlock before unlocking it via the app.");
        }
        
//        else if ([title isEqualToString:kLocalString(@"Disable unlock via Wi-fi")]){
//            model.style = 2;
//            model.switchValue = _settingInfo ? _settingInfo[@"isOpenWifiModel"] : kSTRING(@(kCurClickDevice.isOpenWifiModel));
//        }
//        else if ([title isEqualToString:kLocalString(@"Disable unlock via Bluetooth")]){
//            model.style = 2;
//            model.switchValue = _settingInfo ? _settingInfo[@"isOpenBlueToothModel"] : kSTRING(@(kCurClickDevice.isOpenBlueToothModel));
//        }
        
        [section1 addObject:model];
    }];
    
    NSMutableArray *section2 = [NSMutableArray new];
    NSArray *titles2 = @[kLocalString(@"Striking alarm"),kLocalString(@"Burning alarm"),kLocalString(@"Email notification"),kLocalString(@"Change notification Email")];
    
    [titles2 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        SLDeviceSettingModel *model = [SLDeviceSettingModel new];
        model.title = title;
        model.sectionName = kLocalString(@"Active safety protection");
        if ([title isEqualToString:kLocalString(@"Lock alarm volume")]) {
            NSString *voice = _settingInfo ? _settingInfo[@"voice"] : kCurClickDevice.voice;
            if ([voice isEqualToString:@"0"]) {
                model.content = kLocalString(@"Mute");
            }else if ([voice isEqualToString:@"1"]){
                model.content = kLocalString(@"Small");
            }else if ([voice isEqualToString:@"2"]){
                model.content = kLocalString(@"Medium");
            }else if ([voice isEqualToString:@"3"]){
                model.content = kLocalString(@"Large");
            }
            _curVoice = model.content;
            model.contentColor = KColor_O;
        }else if ([title isEqualToString:kLocalString(@"Striking alarm")]){
            model.style = 2;
            model.switchValue = _settingInfo ? _settingInfo[@"isOpenStrikingAlarm"] : kSTRING(@(kCurClickDevice.isOpenStrikingAlarm));
        }
        else if ([title isEqualToString:kLocalString(@"Burning alarm")]){
            model.style = 2;
            model.switchValue = _settingInfo ? _settingInfo[@"isOpenBurningAlarm"] : kSTRING(@(kCurClickDevice.isOpenBurningAlarm));
        }
        else if ([title isEqualToString:kLocalString(@"Email notification")]){
            model.style = 2;
            model.switchValue = kSTRING(@(kCurClickDevice.isOpenPush));
        }else if ([title isEqualToString:kLocalString(@"Change notification Email")]){
            _emailCellModel = model;
            model.desc = kReplace(kCurClickDevice.pushEmail, kUserInfo.email);
        }
        [section2 addObject:model];
    }];
    if (!kCurClickDevice.isOpenPush) {
        [section2 removeObject:_emailCellModel];
    }
    
    NSMutableArray *section4 = [NSMutableArray new];
    NSArray *titles4 = @[kLocalString(@"Battery"),kLocalString(@"Firmware"),kLocalString(@"Serial number"),kLocalString(@"BLE MAC")];
    [titles4 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        SLDeviceSettingModel *model = [SLDeviceSettingModel new];
        model.title = title;
        model.sectionName = kLocalString(@"About");
        if ([title isEqualToString:kLocalString(@"Firmware")]) {
            model.content = _baseInfo ? _baseInfo[@"version"] : kReplace(kCurClickDevice.firmware, @"-");
            model.contentColor = KColor_O;
        }else if ([title isEqualToString:kLocalString(@"Battery")]){
            model.style = 3;
            NSString *battery = _statusInfo ? _statusInfo[@"batteryLevel"] : kReplace(kCurClickDevice.deviceElectricQty, @"-");
            model.content = [NSString stringWithFormat:@"%@%%",battery];
        }else if ([title isEqualToString:kLocalString(@"Serial number")]){
            model.style = 3;
            model.content = _baseInfo ? kReplace(_baseInfo[@"sn"], @"-") : kReplace(kCurClickDevice.serialNumber, @"-");
        }else if ([title isEqualToString:kLocalString(@"BLE MAC")]){
            model.style = 3;
            model.content = _baseInfo ? _baseInfo[@"mac"] : kReplace(kCurClickDevice.mac, @"-");
        }
        [section4 addObject:model];
    }];
    
    NSMutableArray *section5 = [NSMutableArray new];
    NSArray *titles5 = @[kLocalString(@"Connected bridge")];
    [titles5 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        SLDeviceSettingModel *model = [SLDeviceSettingModel new];
        model.title = title;
        model.sectionName = kLocalString(@"Accessories");
        model.footDesc = kLocalString(@"HEXFORCE™ Bridge can let you get Active Safety Alarm when you have internet connection.");
        [section5 addObject:model];
    }];
    
    [_dataArray addObject:section1];
    [_dataArray addObject:section2];
//    [_dataArray addObject:section3];
    [_dataArray addObject:section4];
    if (kCurClickDevice.bridgeDeviceNo.length > 0) {
        [_dataArray addObject:section5];
    }
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sections = _dataArray[section];
    return sections.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLDeviceSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLDeviceSettingModel *model = _dataArray[indexPath.section][indexPath.row];
    cell.model = model;
    
    NSArray *sections = _dataArray[indexPath.section];
    cell.line.hidden = indexPath.row == sections.count-1;
    CGFloat height = [SLDeviceSettingCell cellHeightWith:model];
    [cell.contentView setRoundedCorners:0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, height)];
    if (sections.count == 1) {
        [cell.contentView setRoundedCorners:20 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, height)];
    }else{
        if (indexPath.row == sections.count-1) {
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight frame:CGRectMake(0, 0, kScreenWidth-40, height)];
        }else if (indexPath.row == 0){
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerTopLeft | UIRectCornerTopRight frame:CGRectMake(0, 0, kScreenWidth-40, height)];
        }
    }
    kWeakSelf(self);
    [cell setSwitchBlock:^(NSInteger isOpen) {
        [weakself switchSettingWith:isOpen model:model];
    }];
    
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLDeviceSettingModel *model = _dataArray[indexPath.section][indexPath.row];
    return [SLDeviceSettingCell cellHeightWith:model];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    NSArray *sections = _dataArray[section];
    SLDeviceSettingModel *model = sections[0];
    if (model.footDesc.length > 0) {
        return 60;
    }
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    UILabel *label = [headview viewWithTag:100];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 50);
        if (!label) {
            label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, kScreenWidth-80, 15)];
            label.textColor =  kHexColor(@"#4D4D4D");
            label.font = kFont(14);
            label.tag = 100;
            [headview addSubview:label];
        }
    }
    NSArray *sections = _dataArray[section];
    SLDeviceSettingModel *model = sections[0];
    label.text = model.sectionName;
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    UILabel *label = [footerView viewWithTag:100];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 10);
        footerView.contentView.backgroundColor = KClearColor;
        if (!label) {
            label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth-80, 60)];
            label.textColor =  kHexColor(@"#808080");
            label.font = kFont(14);
            label.numberOfLines = 0;
            label.tag = 100;
            [footerView addSubview:label];
        }
    }
    NSArray *sections = _dataArray[section];
    SLDeviceSettingModel *model = sections[0];
    if (model.footDesc.length > 0) {
        footerView.height = 60;
    }else{
        footerView.height = 10;
    }
    label.text = model.footDesc;
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SLDeviceSettingModel *model = _dataArray[indexPath.section][indexPath.row];
    if ([model.title isEqualToString:kLocalString(@"Change notification Email")]) {
        SLChangeNotifyVC *vc = [[SLChangeNotifyVC alloc] init];
        kWeakSelf(self);
        [vc setChangeEmailBlock:^(NSString * _Nonnull newEmail) {
            [weakself refresSubViews];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.title isEqualToString:kLocalString(@"Connected bridge")]){
        SLBridgeInfoVC *vc = [[SLBridgeInfoVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.title isEqualToString:kLocalString(@"Firmware")]){
        SLUpdateFirmVC *vc = [[SLUpdateFirmVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.title isEqualToString:kLocalString(@"Set hot area")]){
        SLNearByVC *vc = [[SLNearByVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.title isEqualToString:kLocalString(@"Lock alarm volume")]){
        NSInteger index = [self.voiceArray indexOfObject:_curVoice];
        [self.voicePicker selectRow:index inComponent:0 animated:NO];
        [self.voicePicker show];
    }else if ([model.title isEqualToString:kLocalString(@"Lock name")]){
        [self showInputView];
    }
    
}

-(void)showInputView{
    kWeakSelf(self);
    __weak SLInputAlertView *alert = [SLInputAlertView viewFromXIB];
    alert.titleLbl.text = kLocalString(@"Edit Lock Name");
    [alert.tf setPlaceholderWithPlaceholderText:kLocalString(@"Edit Lock Name") withColor:KColor_placeholdar withFont:kFont(16)];
    [alert setBtnBlock:^(NSString *text, NSInteger btnIndex) {
        if (btnIndex == 2) {
            [alert removeFromSuperview];
            return;
        }
        if (btnIndex == 1) {
            if (text.length == 0) {
                kShowToast(@"Enter lock name");
                return;
            }
            [alert removeFromSuperview];
            [ZCTool showLoadingOnKeyWindow];
            NSDictionary *params = @{@"deviceName":text};
            [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [ZCTool hideLoadingOnKeyWindow];
                if (!isSuccessed) {
                    kShowToast(message);
                    return;
                }
                //修改成功
                SLDeviceSettingModel *model = weakself.dataArray[0][0];
                model.content = text;
                kCurClickDevice.deviceName = text;
                [weakself.tableView reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
                kNotifyRefreshDevcieList;
            }];
        }
    }];
    [kAppWindow addSubview:alert];
}

-(void)configPickers{
    _voiceArray = @[kLocalString(@"Mute"),kLocalString(@"Small"),kLocalString(@"Medium"),kLocalString(@"Large")];
    _voicePicker = [[XZPickView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) title:kLocalString(@"Voice")];
    _voicePicker.delegate = self;
    _voicePicker.dataSource = self;
}

-(NSString *)pickerView:(XZPickView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return _voiceArray[row];
}

-(NSInteger)numberOfComponentsInPickerView:(XZPickView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(XZPickView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _voiceArray.count;
}

- (void)pickView:(XZPickView *)pickerView confirmButtonClick:(UIButton *)button {
    NSInteger row = [pickerView selectedRowInComponent:0];
    _curVoice = _voiceArray[row];
    NSInteger voice = 0;
    if ([_curVoice isEqualToString:kLocalString(@"Mute")]) {
        voice = 0;
    }else if ([_curVoice isEqualToString:kLocalString(@"Small")]){
        voice = 1;
    }else if ([_curVoice isEqualToString:kLocalString(@"Medium")]){
        voice = 2;
    }else if ([_curVoice isEqualToString:kLocalString(@"Large")]){
        voice = 3;
    }
    kWeakSelf(self);
    [ZCTool showLoadingOnKeyWindow];
    [[SLBluetoothManager sharedManager] setDeviceVoice:voice finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
        [weakself hanldeSettingFinish:isSuccess key:@"voice" value:kSTRING(@(voice))];
    }];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, SafeAreaTopHeight, kScreenWidth-40, kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
